package com.levy.utils;

import java.io.UnsupportedEncodingException;

/**
 * 中文乱码转码
 * @author YMQ 20170314
 *
 */
public class GarbledUtil {

	
	public static String toChinese(String text,String encode){
		String encodeStr = getEncoding(text);
		if(encodeStr.equals("UTF-8")||encodeStr.equals("GB2312")){
			return text;
		}else{
			if(encode.toUpperCase().equals("UTF-8")){
				return toChineseUtf8( text);
			}else{
			    return	toChineseGb2312( text);
			}
		}
	}
	
	public static String toChineseUtf8(String text) {
		return getEncodingStr("utf-8", text);
	}
	
	public static String toChineseGb2312(String text) {
		return getEncodingStr("GB2312", text);
	}
	
	
	public static String getEncodingStr(String desEncode,String text){
		String encodeStr = getEncoding(text);
		if(encodeStr.equals(desEncode.toUpperCase())){
			return text;
		}
		String textStr = null;
		try {
			textStr = new String(text.getBytes(encodeStr),desEncode);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return text;
		}
		return textStr;
	}
	
	private static String getEncoding(String str) {        
	       String encode = "GB2312";        
	      try {        
	          if (str.equals(new String(str.getBytes(encode), encode))) {        
	               String s = encode;        
	              return s;        
	           }        
	       } catch (Exception exception) {        
	       }        
	       encode = "ISO-8859-1";        
	      try {        
	          if (str.equals(new String(str.getBytes(encode), encode))) {        
	               String s1 = encode;        
	              return s1;        
	           }        
	       } catch (Exception exception1) {        
	       }        
	       encode = "UTF-8";        
	      try {        
	          if (str.equals(new String(str.getBytes(encode), encode))) {        
	               String s2 = encode;        
	              return s2;        
	           }        
	       } catch (Exception exception2) {        
	       }        
	       encode = "GBK";        
	      try {        
	          if (str.equals(new String(str.getBytes(encode), encode))) {        
	               String s3 = encode;        
	              return s3;        
	           }        
	       } catch (Exception exception3) {        
	       }        
	      return "";        
	   }

	/**
	 * 字符串转换unicode
	 */
	public static String string2Unicode(String string) {

		StringBuffer unicode = new StringBuffer();

		for (int i = 0; i < string.length(); i++) {

			// 取出每一个字符
			char c = string.charAt(i);

			// 转换为unicode
			unicode.append("\\u" + Integer.toHexString(c));
		}

		return unicode.toString();
	}

}
